package com.wwt.mondodb.controller;

import com.wwt.mondodb.entity.Comment;
import com.wwt.mondodb.entity.User;
import com.wwt.mondodb.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class CommentController {
    @Autowired
    private CommentService commentService;
    @GetMapping("/update")
    public String update (String id, Model model, HttpServletRequest request){
        HttpSession session=request.getSession();
        User user= (User) session.getAttribute("user");
        boolean a=commentService.update(id);
        if (!a){
            return "loser";
        }
        model.addAttribute("user",user);
        model.addAttribute("state",commentService.list());
        return "list";
    }
    @GetMapping("/list")
    public String list( Model model, HttpServletRequest request){
        HttpSession session=request.getSession();
        User user= (User) session.getAttribute("user");
        model.addAttribute("user",user);
        model.addAttribute("state",commentService.list());
        return "list";
    }
    @GetMapping("/delte")
    public String delte(String id, Model model,HttpServletRequest request){
        boolean a=commentService.del(id);
        if (!a){
            return "loser";
        }
        HttpSession session=request.getSession();
        User user= (User) session.getAttribute("user");
        model.addAttribute("user",user);
        model.addAttribute("state",commentService.list());
        return "list";
    }
    @PostMapping("/add")
    @ResponseBody
    public boolean add(Comment comment,Model model,HttpServletRequest request){
        HttpSession session=request.getSession();
        User user= (User) session.getAttribute("user");
        comment.setUserId(user.getUserId());
        comment.setNickname(user.getNickname());
        commentService.add(comment);
        model.addAttribute("user",user);
        model.addAttribute("state",commentService.list());
        return true;
    }
}
